<!--
  API日志管理主页面
  @description SOP API日志管理的列表页面，包含搜索、表格、分页、操作等功能
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="80px"
      class="-mb-15px"
    >
      <el-form-item :label="t('sop.apiLog.traceId')" prop="traceId">
        <el-input
          v-model="queryParams.traceId"
          :placeholder="t('sop.common.pleaseInput') + t('sop.apiLog.traceId')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('sop.apiLog.appId')" prop="appId">
        <el-input
          v-model="queryParams.appId"
          :placeholder="t('sop.common.pleaseInput') + t('sop.apiLog.appId')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('sop.apiLog.merchantNo')" prop="merchantNo">
        <el-input
          v-model="queryParams.merchantNo"
          :placeholder="t('sop.common.pleaseInput') + t('sop.apiLog.merchantNo')"
          clearable
          style="width: 180px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('sop.apiLog.apiPath')" prop="apiPath">
        <el-input
          v-model="queryParams.apiPath"
          :placeholder="t('sop.common.pleaseInput') + t('sop.apiLog.apiPath')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('sop.apiLog.httpMethod')" prop="httpMethod">
        <el-select
          v-model="queryParams.httpMethod"
          :placeholder="t('sop.common.pleaseSelect') + t('sop.apiLog.httpMethod')"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="method in httpMethods"
            :key="method"
            :label="method"
            :value="method"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('sop.apiLog.responseCode')" prop="responseCode">
        <el-select
          v-model="queryParams.responseCode"
          :placeholder="t('sop.common.pleaseSelect') + t('sop.apiLog.responseCode')"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="(label, value) in responseCodeOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('sop.apiLog.requestTime')" prop="requestTime">
        <el-date-picker
          v-model="queryParams.requestTime"
          type="datetimerange"
          range-separator="-"
          :start-placeholder="t('sop.common.startTime')"
          :end-placeholder="t('sop.common.endTime')"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 350px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          {{ t('sop.common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          {{ t('sop.common.reset') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['sop:api-log:export']"
        >
          <Icon class="mr-5px" icon="ep:download" />
          {{ t('sop.common.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id">
      <el-table-column :label="t('sop.apiLog.traceId')" align="center" prop="traceId" width="200">
        <template #default="scope">
          <el-text class="trace-id-text" copyable>{{ scope.row.traceId }}</el-text>
        </template>
      </el-table-column>
      <el-table-column :label="t('sop.apiLog.appId')" align="center" prop="appId" width="180">
        <template #default="scope">
          <el-text class="app-id-text" copyable>{{ scope.row.appId }}</el-text>
        </template>
      </el-table-column>
      <el-table-column :label="t('sop.apiLog.merchantNo')" align="center" prop="merchantNo" width="150" />
      <el-table-column :label="t('sop.apiLog.httpMethod')" align="center" prop="httpMethod" width="100">
        <template #default="scope">
          <el-tag :type="getHttpMethodTagType(scope.row.httpMethod)">
            {{ scope.row.httpMethod }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('sop.apiLog.apiPath')" align="center" prop="apiPath" min-width="200" />
      <el-table-column :label="t('sop.apiLog.responseCode')" align="center" prop="responseCode" width="100">
        <template #default="scope">
          <el-tag :type="getResponseCodeTagType(scope.row.responseCode)">
            {{ scope.row.responseCode }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('sop.apiLog.responseTime')" align="center" prop="responseTime" width="120">
        <template #default="scope">
          <span :class="getResponseTimeClass(scope.row.responseTime)">
            {{ scope.row.responseTime }}ms
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="t('sop.apiLog.clientIp')" align="center" prop="clientIp" width="140" />
      <el-table-column
        :label="t('sop.apiLog.requestTime')"
        align="center"
        prop="requestTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column :label="t('sop.common.operation')" align="center" width="120" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row)"
            v-hasPermi="['sop:api-log:query']"
          >
            {{ t('sop.common.view') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- API日志详情 -->
  <ApiLogDetail ref="detailRef" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { dateFormatter } from '@/utils/formatTime'
import { useMessage } from '@/hooks/web/useMessage'
import { 
  getApiLogPageApi, 
  exportApiLogApi
} from '@/api/sop/apiLog'
import type { ApiLogVO, ApiLogPageReqVO } from '@/api/sop/types'
import { ContentWrap } from '@/components/ContentWrap'
import { Icon } from '@/components/Icon'
import Pagination from '@/components/Pagination/index.vue'
import ApiLogDetail from './ApiLogDetail.vue'

defineOptions({ name: 'SopApiLog' })

const { t } = useI18n()
const message = useMessage()

// 加载状态
const loading = ref(true)
const exportLoading = ref(false)

// 列表数据
const list = ref<ApiLogVO[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<ApiLogPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  traceId: undefined,
  appId: undefined,
  merchantNo: undefined,
  apiPath: undefined,
  httpMethod: undefined,
  responseCode: undefined,
  requestTime: undefined
})

// 表单引用
const queryFormRef = ref<FormInstance>()
const detailRef = ref()

// 选项数据
const httpMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']

const responseCodeOptions = {
  200: '200 - 成功',
  400: '400 - 请求错误',
  401: '401 - 未授权',
  403: '403 - 禁止访问',
  404: '404 - 未找到',
  429: '429 - 限流',
  500: '500 - 服务器错误'
}

/**
 * 查询列表
 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getApiLogPageApi(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('查询API日志列表失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/**
 * 查看详情
 */
const openDetail = (row: ApiLogVO) => {
  detailRef.value.open(row)
}

/**
 * 导出按钮操作
 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    await exportApiLogApi(queryParams)
    message.success(t('sop.common.exportSuccess'))
  } catch (error) {
    console.error('导出API日志数据失败:', error)
  } finally {
    exportLoading.value = false
  }
}

// 标签类型获取函数
const getHttpMethodTagType = (method: string) => {
  const methodMap = {
    'GET': 'primary',
    'POST': 'success',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  }
  return methodMap[method] || ''
}

const getResponseCodeTagType = (code: number) => {
  if (code >= 200 && code < 300) return 'success'
  if (code >= 300 && code < 400) return 'info'
  if (code >= 400 && code < 500) return 'warning'
  if (code >= 500) return 'danger'
  return ''
}

const getResponseTimeClass = (time: number) => {
  if (time < 100) return 'fast-response'
  if (time < 500) return 'normal-response'
  if (time < 1000) return 'slow-response'
  return 'very-slow-response'
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.trace-id-text {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.app-id-text {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.fast-response {
  color: #67c23a;
  font-weight: bold;
}

.normal-response {
  color: #409eff;
}

.slow-response {
  color: #e6a23c;
  font-weight: bold;
}

.very-slow-response {
  color: #f56c6c;
  font-weight: bold;
}
</style>
